package com.itheima.controller;


import com.itheima.pojo.Admin;
import com.itheima.pojo.CategoryMenu;
import com.itheima.service.AuthService;
import com.itheima.utils.CookieUtils;
import com.itheima.utils.JwtUtil;
import com.itheima.utils.Result;
import com.itheima.vo.Assignbody;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

@RestController
@CrossOrigin
@RequestMapping("/auth")
public class AuthController {

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private AuthService authService;

    //注册管理员
    @PostMapping("/register")
    public Result register(@RequestBody Assignbody assignbody) {

        if (authService.findByUserNnme(assignbody.getUserName())) {
            return new Result("error", "用户名重复");
        }

        String email = assignbody.getEmail();
        String mobile = assignbody.getMobile();

        if ((email.equals(null) || email.length() <= 0) && (mobile.equals(null) || mobile.length() <= 0)) {
            return new Result("error", "邮箱和电话至少一个不能为空");
        }

        if (mobile.length() >= 11) {
            return new Result("error", "电话输入错误");
        }

        String[] split = email.split("\\.", 3);
        if (!split[0].equals("www")) {
            return new Result("error", "邮箱格式错误");
        } else if (!split[2].equals("com")) {
            return new Result("error", "邮箱格式错误");
        } else if (split[1].indexOf("@") == -1) {
            return new Result("error", "邮箱格式错误");
        }

        try {
            authService.register(assignbody);
            return new Result("success", "操作成功");
        } catch (Exception e) {
            e.printStackTrace();
            return new Result("error", "操作失败");
        }
    }


    @GetMapping("/getMenu")
    public Result GetMenu(HttpServletRequest request) throws Exception {
        String token = request.getHeader("Authorization");
        String username = JwtUtil.parseJWT(token).getSubject();
        Map<String, List<CategoryMenu>> map1 = authService.getMenu(username);
        return new Result("success", map1);
    }


    @PostMapping("/updatePassWord")
    public Result updatePassWord(@RequestParam("userInfo") String userName, @RequestParam("passWord") String passWord, @RequestParam("newPassWord") String newPpassWord) {
        Result result = authService.login(userName, passWord);
        if (!result.equals("执行成功")) {
            return result;
        }

        try {
            authService.updatePassWord(userName, newPpassWord);
            return new Result("success", "操作成功");
        } catch (Exception e) {
            e.printStackTrace();
            return new Result("error", "操作失败");
        }
    }

    @PostMapping("/login")
    public Result login(String username, String password, String isRememberMe, HttpServletRequest request) {
        if (StringUtils.isEmpty(username) || StringUtils.isEmpty(password)) {
            return new Result("error", "账号或密码不能为空");
        }


        String remoteAddr = request.getRemoteAddr();
        Integer i = (Integer) redisTemplate.boundValueOps(username).get();
       /* if (i != null && i == 0) {
            return new Result(Result.ERROR, "密码错误次数过多,已被锁定30分钟");
        }*/
        Admin admin = null;
        try {
            admin = authService.login(username, password, remoteAddr);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result("error", "用户名或密码错误,错误");// + i + "次以后,账户将被锁定30分钟");
        }
       /* if (!b) {
            //if (i == null) {
                //redisTemplate.opsForValue().set(username, 4, 60 * 30, TimeUnit.SECONDS);
                //return new Result(Result.ERROR, "用户名或密码错误,错误4次以后,账户将被锁定30分钟");
            }
            //redisTemplate.opsForValue().set(username, i - 1, 60 * 30, TimeUnit.SECONDS);
            return new Result(Result.ERROR, "用户名或密码错误,错误");// + i + "次以后,账户将被锁定30分钟");
        }*/
        //redisTemplate.delete(username);
        String jwt = JwtUtil.createJWT(UUID.randomUUID().toString(), username, 60 * 30 * 1000L);


        String redis = jwt;
//        String loginRedisKey = TokenUtils.token("user",user.getUid());
        //序列化为String  防止key值出现\xac\xed\x00\x05t\x00前缀
        RedisSerializer stringSerializer = new StringRedisSerializer();
        Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class);//序列化为Json
        redisTemplate.setKeySerializer(stringSerializer);
        redisTemplate.setValueSerializer(jackson2JsonRedisSerializer);
        redisTemplate.setHashKeySerializer(stringSerializer);
        redisTemplate.setHashValueSerializer(jackson2JsonRedisSerializer);

        //redisTemplte中存入username和password和uid
        redisTemplate.boundHashOps(redis).put("username", username);
        redisTemplate.boundHashOps(redis).put("password", password);
        redisTemplate.boundHashOps(redis).put("uid", admin.getUid());
        redisTemplate.boundHashOps(redis).put("token", jwt);
        //设置redis保存时间30min
        redisTemplate.expire(redis, 30, TimeUnit.MINUTES);


        CookieUtils.setCookie("username", username, 60 * 60 * 24 * 7);
        CookieUtils.setCookie("password", password, 60 * 60 * 24 * 7);


        CookieUtils.setCookie("Authorization", jwt, 60 * 30);
        Map map = new HashMap();
        map.put("token", jwt);
        return new Result("success", map);
    }


    @PostMapping("/logout")
    public Result logout(HttpServletResponse response) {
        Cookie cookie = new Cookie("Authorization", "");
        cookie.setMaxAge(0);
        response.addCookie(cookie);
        return new Result("success", "操作成功");
    }

    @GetMapping("/info")
    public Result info(String token) throws Exception {
        String username = JwtUtil.parseJWT(token).getSubject();
        Map<String, Object> map = authService.getInfo(username);
        map.put("token", token);
        return new Result("success", map);
    }

}
